package com.lam.dormitory.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lam.dormitory.util.ShiroUtils;
import com.lam.dormitory.entity.Permission;
import com.lam.dormitory.entity.RolePermission;
import com.lam.dormitory.service.IPermissionService;
import com.lam.dormitory.service.IRolePermissionService;
import com.lam.dormitory.util.ResponseTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lam
 * @since 2019-12-20
 */
@Api(tags = "权限接口")
@RestController
@RequestMapping("/permission")
public class PermissionController {
    /**
     * 1:全部资源，2：菜单资源
     */
    private static final String[] MENU_FLAG = {"1", "2"};
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IRolePermissionService rolePermissionService;


    @ApiOperation(value = "权限列表数据", notes = "根据条件(permissionId,name,description,url,perms)权限列表数据 flag=1:全部资源，flag=2：菜单资源")
    @PostMapping("/list")
    @RequiresRoles(value = {"superadmin", "admin"}, logical = Logical.OR)
    //这里代表的时要走这个方法模块中就得有角色管理这个模块，没有就拒绝访问
//    @RequiresPermissions("permission:list")
    public ResponseTemplate loadPermissions(Permission permission, @RequestParam(defaultValue = "1") String flag,
                                            @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "0") Integer pageSize) {
        if (StringUtils.isBlank(flag) || MENU_FLAG[0].equals(flag)) {
            PageHelper.startPage(pageNum, pageSize);
            List<Permission> permissionListList = permissionService.selectByPermission(permission);
            PageInfo<Permission> pages = new PageInfo<>(permissionListList);
            return new ResponseTemplate(200, "获取全部资源成功", permissionListList, pages.getTotal());
        } else if (MENU_FLAG[1].equals(flag)) {
            PageHelper.startPage(pageNum, pageSize);
            List<Permission> permissionListList = permissionService.selectAllMenuName();
            PageInfo<Permission> pages = new PageInfo<>(permissionListList);
            return new ResponseTemplate(200, "获取菜单资源成功", permissionListList, pages.getTotal());
        }
        return new ResponseTemplate(500, "获取资源失败");
    }


    /*添加权限*/
    @ApiOperation(value = "添加权限", notes = "添加权限")
    @PostMapping("/add")
//    @RequiresPermissions("permission:add")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate addPermission(Permission addPermission) {
        String name = addPermission.getName();
        Permission permission = permissionService.selectPermissionByName(name);
        if (null != permission) {
            return new ResponseTemplate(500, "权限名已存在");
        }
        addPermission.setStatus(1);
        Date date = new Date();
        addPermission.setCreateTime(date);
        addPermission.setUpdateTime(date);
        boolean result = permissionService.save(addPermission);
        if (result) {
            //清除缓存
//            String username = ShiroUtils.getUserInfo().getUsername();
//            ShiroUtils.deleteCache(username, false);
            return new ResponseTemplate(200, "权限添加成功");
        } else {
            return new ResponseTemplate(500, "权限添加失败");
        }
    }

    /*删除权限*/
    @ApiOperation(value = "删除权限", notes = "根据permissionId删除权限")
    @PostMapping("/delete")
//    @RequiresPermissions("permission:delete")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate deletePermission(Long permissionId) {
        int subPermsByPermissionIdCount = permissionService.selectSubPermsByPermissionId(permissionId);
        if (subPermsByPermissionIdCount > 0) {
            return new ResponseTemplate(500, "该资源存在下级资源，无法删除！");
        }
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Permission::getPermissionId, permissionId);

        QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(RolePermission::getPermissionId, permissionId);
        boolean a = permissionService.remove(wrapper);
        boolean b = rolePermissionService.remove(queryWrapper);
        if (a||b) {
            return new ResponseTemplate(200, "删除权限成功");
        } else {
            return new ResponseTemplate(500, "删除权限失败");

        }
    }

    /*编辑权限*/
    @ApiOperation(value = "编辑权限", notes = "编辑权限")
    @PostMapping("/edit")
//    @RequiresPermissions("permission:edit")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate editPermission(Permission permission) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Permission::getPermissionId, permission.getPermissionId());
        permission.setUpdateTime(new Date());
        boolean update = permissionService.update(permission, wrapper);
        if (update) {
            return new ResponseTemplate(200, "编辑权限成功");
        } else {
            return new ResponseTemplate(500, "编辑权限失败");
        }
    }

    /*获取当前登录用户的菜单*/
    @ApiOperation(value = "获取当前登录用户的菜单", notes = "获取当前登录用户的菜单")
    @PostMapping("/menu")
    @RequiresRoles(value = {"admin", "superadmin", "student"}, logical = Logical.OR)
    public ResponseTemplate getMenus(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "0") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Permission> permissionList = permissionService.selectMenuByUserId(ShiroUtils.getUserInfo().getUserId());
        PageInfo<Permission> pages = new PageInfo<>(permissionList);
        return new ResponseTemplate(200, "获取当前登录用户的菜单成功", permissionList, pages.getTotal());
    }

    /*权限详情*/
    @ApiOperation(value = "权限详情", notes = "根据permissionId查询权限详情 ")
//    @RequiresPermissions("permission:edit")
    @PostMapping("/detail")
    @RequiresRoles(value = {"admin", "superadmin"}, logical = Logical.OR)
    public ResponseTemplate permDetail(Long permissionId) {
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Permission::getPermissionId, permissionId);
        List<Permission> permissionList = permissionService.list(wrapper);
        return new ResponseTemplate(200, "查询成功", permissionList);
    }
}
